package net.lcheng.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.lcheng.commons.utils.PageList;

import net.lcheng.dao.BaseShippingCompanyMapper;
import net.lcheng.dao.OOrderHistoryMapper;
import net.lcheng.dao.OOrderMapper;
import net.lcheng.dao.OOrderRefundMapper;
import net.lcheng.model.*;
import net.lcheng.service.TradeManageService;
import net.lcheng.vo.OrderConditionsSelectModel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * Created by LV on 2016/7/4.
 */
@Service("tradeManageService")
public class TradeManageServiceImpl implements TradeManageService {
    @Resource
    private OOrderMapper orderMapper;
    @Resource
    private OOrderHistoryMapper orderHistoryMapper;
    @Resource
    private BaseShippingCompanyMapper shippingCompanyMapper;
    @Resource
    private OOrderRefundMapper orderRefundMapper;

    /**
     * 由店铺ID,shopId和订单状态orderStatus获取所有订单
     * @param shopId 店铺ID
     * @param orderStatus 订单状态
     * @param pageSize pageSize
     * @param pageIndex startPage
     * @return pageList
     */
    @Override
    public PageList<OOrder> getAllOrdersByShopIdAndOrderStatus(int shopId, int orderStatus, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex,pageSize);

        OOrderExample example=new OOrderExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andOrderStatusEqualTo(orderStatus);
        List<OOrder> list=orderMapper.selectByExample(example);
//
//        List<OrderModel> orderModelList=new ArrayList<>();
//
//        for( int i=0;i<list.size();i++){
//            OrderModel orderModel=new OrderModel();
//            orderModel.setoOrder(list.get(i));
//            //将json串类型的orderItems转换成OrderProductsEntity对象
//            List<OrderProductsEntity> entities= JSON.parseArray(list.get(i).getOrderProducts(),OrderProductsEntity.class);
//            orderModel.setOrderProductsEntityList(entities);
//            orderModelList.add(orderModel);
//        }

        PageInfo<OOrder> pageInfo=new PageInfo<>(list);
        PageList<OOrder> pageList=new PageList<>();
        pageList.list=pageInfo.getList();
        pageList.pageIndex=pageInfo.getPageNum();
        pageList.pageSize=pageInfo.getPageSize();
        pageList.totalPage=pageInfo.getPages();
        pageList.totalCount=pageInfo.getTotal();

        return pageList;
    }

    /**
     * 由店铺ID,shopId和订单状态orderStatus获取所有订单
     * @param shopId 店铺Id
     * @param orderStatus 订单状态
     * @return list
     */
    @Override
    public List<OOrder> getAllOrdersByShopIdAndOrderStatus(int shopId, int orderStatus) {
        OOrderExample example=new OOrderExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andOrderStatusEqualTo(orderStatus);
        return orderMapper.selectByExample(example);
    }

    /**
     * 获取所有订单
     * @param shopId 店铺Id
     * @param buyerUserId 买家用户Id
     * @param orderStatus 订单状态
     * @return list
     */
    @Override
    public List<OOrder> getAllOrders(int shopId, String buyerUserId, int orderStatus) {
        OOrderExample example=new OOrderExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andOrderStatusEqualTo(orderStatus)
                .andBuyerUserIdEqualTo(buyerUserId);
        return orderMapper.selectByExample(example);
    }

    /**
     * 由shopId获取所有订单列表
     * @param shopId 店铺ID
     * @param pageSize 页面大小
     * @param pageIndex 页面索引
     * @return pageList
     */
    @Override
    public PageList<OOrder> getAllOrdersByShopId(int shopId, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex,pageSize);

        OOrderExample example=new OOrderExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId);

        List<OOrder> list=orderMapper.selectByExample(example);
//        List<OrderModel> orderModelList=new ArrayList<>();
//        //测试用
//        OrderProductsEntity orderProductsEntity=new OrderProductsEntity();
//        orderProductsEntity.setId(UUID.randomUUID().toString());
//        orderProductsEntity.setTitle("电脑");
//        orderProductsEntity.setCode("465416161");
//        orderProductsEntity.setImage("www.baidu.img");
//        orderProductsEntity.setPrice(new BigDecimal(15646));
//        orderProductsEntity.setQuantity(55);
//        List<OrderProductsEntity> entityList=new ArrayList<>();
//        entityList.add(orderProductsEntity);
//        System.out.println(JSON.toJSONString(entityList));

//        for( int i=0;i<list.size();i++){
//            OrderModel orderModel=new OrderModel();
//            orderModel.setoOrder(list.get(i));
//            //将json串类型的orderItems转换成OrderProductsEntity对象
//            List<OrderProductsEntity> entityList= JSON.parseArray(list.get(i).getOrderProducts(),OrderProductsEntity.class);
//            orderModel.setOrderProductsEntityList(entityList);
//            orderModelList.add(orderModel);
//        }

        PageInfo<OOrder> pageInfo=new PageInfo<>(list);
        PageList<OOrder> pageList=new PageList<>();
        pageList.list=pageInfo.getList();
        pageList.pageIndex=pageInfo.getPageNum();
        pageList.pageSize=pageInfo.getPageSize();
        pageList.totalPage=pageInfo.getPages();
        pageList.totalCount=pageInfo.getTotal();

        return pageList;
    }

    /**
     * 由shopId获取所有订单列表
     * @param shopId 店铺ID
     * @return list
     */
    @Override
    public List<OOrder> getAllOrdersByShopId(int shopId) {
        OOrderExample example=new OOrderExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId);

        return orderMapper.selectByExample(example);
    }

    /**
     * 获取所有订单
     * @param shopId 店铺Id
     * @param buyerUserId 买家用户Id
     * @return list
     */
    @Override
    public List<OOrder> getAllOrders(int shopId, String buyerUserId) {
        OOrderExample example=new OOrderExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andBuyerUserIdEqualTo(buyerUserId);

        return orderMapper.selectByExample(example);
    }

    /**
     * 由主键查询订单
     * @param orderId 订单Id
     * @return OOrder
     */
    @Override
    public OOrder getOrderByPrimaryKey(String orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    /**
     * 由订单的主键查询订单的日志
     * @param orderId 订单ID
     * @return list
     */
    @Override
    public List<OOrderHistory> getOrderHistoryByOrderId(String orderId) {
        OOrderHistoryExample example=new OOrderHistoryExample();
        example.createCriteria().andOOrderOrderIdEqualTo(orderId);
        example.setOrderByClause("create_on");//日志按升序排列
        return orderHistoryMapper.selectByExample(example);
    }

    /**
     * 添加订单日志信息
     * @param orderHistory 订单日志
     * @return int
     */
    @Override
    public int addOrderHistory(OOrderHistory orderHistory) {
        return orderHistoryMapper.insertSelective(orderHistory);
    }

    /**
     * 获取物流公司列表
     * @return list
     */
    @Override
    public List<BaseShippingCompany> getAllShippingCompany() {
        BaseShippingCompanyExample example=new BaseShippingCompanyExample();
        example.createCriteria().andStatusEqualTo(1);
        return shippingCompanyMapper.selectByExample(example);
    }

    /**
     * 修改订单信息
     * @param order 订单
     * @return int
     */
    @Override
    public int updateOOrderByPrimaryKey(OOrder order) {
        return orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 获取指定店铺的所有退款订单列表
     * @param shopId 店铺ID
     * @param pageSize 页面大小
     * @param pageIndex 页面索引
     * @return pageList
     */
    @Override
    public PageList<OOrderRefund> getAllRefundOrdersByShopId(int shopId, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex,pageSize);

        OOrderRefundExample example=new OOrderRefundExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId);
        List<OOrderRefund> list=orderRefundMapper.selectByExample(example);

        PageInfo<OOrderRefund> pageInfo=new PageInfo<>(list);
        PageList<OOrderRefund> pageList=new PageList<>();
        pageList.list=pageInfo.getList();
        pageList.pageIndex=pageInfo.getPageNum();
        pageList.pageSize=pageInfo.getPageSize();
        pageList.totalPage=pageInfo.getPages();
        pageList.totalCount=pageInfo.getTotal();

        return pageList;
    }

    /**
     * 获取指定店铺的所有退款订单列表
     * @param shopId 店铺Id
     * @return list
     */
    @Override
    public List<OOrderRefund> getAllRefundOrdersByShopId(int shopId) {
        OOrderRefundExample example=new OOrderRefundExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId);
        return orderRefundMapper.selectByExample(example);
    }

    /**
     * 获取指定的店铺不同状态的退款订单列表
     * @param shopId 店铺ID
     * @param orderStatus 订单状态
     * @param pageSize 单页大小
     * @param pageIndex 页面索引
     * @return pageList
     */
    @Override
    public PageList<OOrderRefund> getAllRefundOrdersByShopIdAndOrderStatus(int shopId, int orderStatus, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex,pageSize);

        OOrderRefundExample example=new OOrderRefundExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                            .andOrderStatusEqualTo(orderStatus);
        List<OOrderRefund> list=orderRefundMapper.selectByExample(example);

        PageInfo<OOrderRefund> pageInfo=new PageInfo<>(list);
        PageList<OOrderRefund> pageList=new PageList<>();
        pageList.list=pageInfo.getList();
        pageList.pageIndex=pageInfo.getPageNum();
        pageList.pageSize=pageInfo.getPageSize();
        pageList.totalPage=pageInfo.getPages();
        pageList.totalCount=pageInfo.getTotal();

        return pageList;
    }

    /**
     * 获取指定的店铺不同状态的退款订单列表
     * @param shopId 店铺Id
     * @param orderStatus 订单状态
     * @return list
     */
    @Override
    public List<OOrderRefund> getAllRefundOrdersByShopIdAndOrderStatus(int shopId, int orderStatus) {
        OOrderRefundExample example=new OOrderRefundExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andOrderStatusEqualTo(orderStatus);
        return orderRefundMapper.selectByExample(example);
    }

    /**
     * 获取指定店铺和用户的所有订单
     * @param shopId 店铺Id
     * @param buyerUserId 买家用户Id
     * @return list
     */
    @Override
    public List<OOrderRefund> getAllRefundOrders(int shopId, String buyerUserId) {
        OOrderRefundExample example=new OOrderRefundExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andBuyerUserIdEqualTo(buyerUserId);
        return orderRefundMapper.selectByExample(example);
    }

    /**
     * 获取指定店铺,用户,订单状态的所有订单
     * @param shopId 店铺Id
     * @param buyerUserId 买家用户Id
     * @param orderStatus 订单状态
     * @return list
     */
    @Override
    public List<OOrderRefund> getAllRefundOrders(int shopId, String buyerUserId, int orderStatus) {
        OOrderRefundExample example=new OOrderRefundExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andOrderStatusEqualTo(orderStatus)
                .andBuyerUserIdEqualTo(buyerUserId);
        return orderRefundMapper.selectByExample(example);
    }

    /**
     * 由主键更新OOrderRefund
     * @param orderRefund 退货订单
     * @return int
     */
    @Override
    public int updateOOrderRefundByPrimaryKey(OOrderRefund orderRefund) {
        return orderRefundMapper.updateByPrimaryKeySelective(orderRefund);
    }

    /**
     * 由主键查询退货订单表
     * @param orderRefundId 退货订单主键
     * @return OOrderRefund
     */
    @Override
    public OOrderRefund getOorderRefundByPrimaryKey(String orderRefundId) {
        return orderRefundMapper.selectByPrimaryKey(orderRefundId);
    }

    /**
     * 多条件查询OOrder表
     * @param model 模型
     * @return PageList
     */
    @Override
    public PageList<OOrder> getOrderListByConditions(int shopId, OrderConditionsSelectModel model, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex,pageSize);

        OOrderExample example=new OOrderExample();
        OOrderExample.Criteria criteria=example.createCriteria();
        criteria.andWxShopShopIdEqualTo(shopId);

        if (model.getOrderNum()!=null&&!model.getOrderNum().equals(""))
            criteria.andOrderNumEqualTo(model.getOrderNum());
        if (model.getOrderStartTime()!=null)
            criteria.andOrderTimeGreaterThanOrEqualTo(model.getOrderStartTime());
        if (model.getOrderEndTime()!=null)
            criteria.andOrderTimeLessThanOrEqualTo(model.getOrderEndTime());
        if (model.getBuyer()!=null&&!model.getBuyer().equals(""))
            criteria.andBuyerUserNameLike(model.getBuyer());
        if (model.getStatus()!=-2)//在接收装换时，如果前端不选，默认为-2
            criteria.andOrderStatusEqualTo(model.getStatus());

        List<OOrder> list=orderMapper.selectByExample(example);

        PageInfo<OOrder> pageInfo=new PageInfo<>(list);
        PageList<OOrder> pageList=new PageList<>();
        pageList.list=pageInfo.getList();
        pageList.pageIndex=pageInfo.getPageNum();
        pageList.pageSize=pageInfo.getPageSize();
        pageList.totalPage=pageInfo.getPages();
        pageList.totalCount=pageInfo.getTotal();

        return pageList;
    }

    /**
     * 多条件查询OOrderRefund
     * @param model 模型
     * @return PageList
     */
    @Override
    public PageList<OOrderRefund> getOrderRefundListByConditions(int shopId, OrderConditionsSelectModel model, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex,pageSize);

        OOrderRefundExample example=new OOrderRefundExample();
        OOrderRefundExample.Criteria criteria=example.createCriteria();
        criteria.andWxShopShopIdEqualTo(shopId);

        if (model.getOrderNum()!=null&&!model.getOrderNum().equals(""))
            criteria.andOrderNumEqualTo(model.getOrderNum());
        if (model.getOrderStartTime()!=null)
            criteria.andOrderTimeGreaterThanOrEqualTo(model.getOrderStartTime());
        if (model.getOrderEndTime()!=null)
            criteria.andOrderTimeLessThanOrEqualTo(model.getOrderEndTime());
        if (model.getBuyer()!=null&&!model.getBuyer().equals(""))
            criteria.andBuyerUserNameLike(model.getBuyer());
        if (model.getStatus()!=-2)//在接收装换时，如果前端不选，默认为-2
            criteria.andOrderStatusEqualTo(model.getStatus());

        List<OOrderRefund> list=orderRefundMapper.selectByExample(example);

        PageInfo<OOrderRefund> pageInfo=new PageInfo<>(list);
        PageList<OOrderRefund> pageList=new PageList<>();
        pageList.list=pageInfo.getList();
        pageList.pageIndex=pageInfo.getPageNum();
        pageList.pageSize=pageInfo.getPageSize();
        pageList.totalPage=pageInfo.getPages();
        pageList.totalCount=pageInfo.getTotal();

        return pageList;
    }

    /**
     * 获得指定订单状态对应的订单数
     * @param shopId 店铺Id
     * @param status 订单状态
     * @return int
     */
    @Override
    public int getOrderCountByOrderStatus(int shopId, int status) {
        OOrderExample example=new OOrderExample();
        example.createCriteria().andWxShopShopIdEqualTo(shopId)
                .andOrderStatusEqualTo(status);
        return orderMapper.countByExample(example);
    }

    /**
     *
     * @param oOrder
     * @return
     */
    @Transactional
    @Override
    public int cancelOrderByBuyer(OOrder oOrder) {
        if (oOrder!=null){
            int status=orderMapper.updateByPrimaryKeySelective(oOrder);
            if (status>0){
                //添加订单记录日志
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());//主键
                history.setoOrderOrderId(oOrder.getOrderId());//原订单ID
                history.setComment("买家已取消订单");
                history.setOrderStatus(-1);
                history.setCreateBy(oOrder.getBuyerUserName());
                history.setCreateOn(new Date());

                int status1=orderHistoryMapper.insertSelective(history);
                if (status1>0)
                    return 1;
                else
                    return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 卖家取消订单
     * @param oOrder 取消的订单
     * @return int
     */
    @Override
    public int cancelOrderBySeller(OOrder oOrder) {
        if (oOrder!=null){
            int status=orderMapper.updateByPrimaryKeySelective(oOrder);
            if (status>0){
                //添加订单记录日志
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());//主键
                history.setoOrderOrderId(oOrder.getOrderId());//原订单ID
                history.setComment("卖家已取消订单");
                history.setOrderStatus(-1);
                history.setCreateBy(oOrder.getBuyerUserName());
                history.setCreateOn(new Date());

                int status1=orderHistoryMapper.insertSelective(history);
                if (status1>0)
                    return 1;
                else
                    return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 买家取消退款订单
     * @param orderRefund 退款订单信息
     * @return int
     */
    @Transactional
    @Override
    public int cancelOrderRefundByBuyer(OOrderRefund orderRefund) {
        if (orderRefund!=null){
            int status=orderRefundMapper.updateByPrimaryKeySelective(orderRefund);
            if (status>0){
                //添加订单记录日志
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());//主键
                history.setoOrderOrderId(orderRefund.getOrderId());//原订单ID
                history.setComment("买家已取消退款订单");
                history.setOrderStatus(1);
                history.setCreateBy(orderRefund.getBuyerUserName());
                history.setCreateOn(new Date());

                int status1=orderHistoryMapper.insertSelective(history);
                if (status1>0)
                    return 1;
                else
                    return 0;
            }
            return 0;
        }
        return 0;
    }

}
